import re

from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView

# Create your views here.
from apps.users.models import User


class UserNameCountView(APIView):
    def get(self,request,username):

        count = User.objects.filter(username=username).count()
        if count > 0:
            return Response({'code':400,'errmsg':'用户名重复，请换一个'})
        else:
            return Response({'code':0,'errmsg':'ok','count':count})


class MobileCountView(APIView):
    """判断手机号是否重复"""
    def get(self,request,mobile):
        count = User.objects.filter(mobile=mobile).count()
        if count > 0:
            return Response({'code':400,'errmsg':'手机号重复，请换一个'})
        else:
            return Response({'code':0,'errmsg':'ok','count':count})


class RegisterView(APIView):
    """用户注册接口"""
    def post(self,request):
        """
        用户名，手机号，密码，确认密码，图形验证码，短信验证码，是否接受协议
        :param request:
        :return:
        """
        username = request.data.get('username')
        mobile = request.data.get('mobile')
        password = request.data.get('password')
        password2 = request.data.get('password2')
        sms_code = request.data.get('sms_code') # Short MeSsage
        allow = request.data.get('allow')

        #校验参数是否都不是空的
        if not all([username,mobile,password,password2,sms_code,allow]):
            return Response({'code':400,'errmsg':'参数不全'})

        #判断用户名是否符合某个正则表达式规则
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$',username):
            return Response({'code':400,'errmsg':'用户名不符合规则'})

        # 判断密码是否符合某个正则表达式的规则
        if not re.match(r'^[a-zA-Z0-9]{8,20}$',password):
            return Response({'code':400,'errmsg':'密码不符合规则'})

        # 比较两次密码是否一致
        if password != password2:
            return Response({'code':400,'errmsg':'两次密码不一致'})

        # 判断手机号是否符合某个正则表达式
        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return Response({'code':400,'errmsg':'手机号不符合规则'})

        #判断是否接受了用户协议
        if allow != True:
            return Response({'code':400,'errmsg':'用户协议格式不正确'})

        #编写注册业务逻辑，使用ORM向数据库中添加一条记录
        try:
            user = User.objects.create_user(username=username,mobile=mobile,password=password)
            return Response({'code':0,'errmsg':'ok'})
        except Exception as e:
            return Response({'code':400,'errmsg':'注册失败'})
